<template>
  <div class="new-carry-over route-page">
    <section class="header">
      <a-page-header
        class="demo-page-header"
        style="border: 1px solid rgb(235, 237, 240)"
        :title="title"
        sub-title=""
        :class="notBack ? 'hide-back' : ''"
        @back="() => $router.go(-1)"
      >
        <div style="display: flex; justify-content: space-between">
          <a-list item-layout="horizontal" style="width: 80%">
            <a-list-item>
              <a-list-item-meta>
                <template #avatar>
                  <!-- <a-avatar
                  src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"
                  size="large"
                /> -->
                  <FileTwoTone style="font-size: 36px" />
                </template>
                <template #title>
                  <a>
                    <span
                      style="font-weight: bold; color: #333333; font-size: 18px"
                    >
                      租客：{{contractDetail?.owner_info?.owner_name}}
                    </span>
                  </a>
                </template>
                <template #description>
                  <div style="font-weight: bold; color: #333333">
                    合同编号： {{contractDetail?.contract_number}}
                  </div>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </a-list>
        </div>
      </a-page-header>
    </section>
    <section class="content">
      <a-row :gutter="12">
        <a-col :span="24">
          <a-card size="small" title="本合同账单">
            <template #extra>
              <a-space>
                <a-checkbox
                  v-model:checked="hiddenZero"
                >
                  隐藏需收/付金额为 0 的账单
                </a-checkbox>
                <a-button
                  :loading="fastLoading"
                  @click="handleFastCarry"
                >
                  快捷结转
                </a-button>
                <a-button
                  @click="resetTableData"
                >
                  重置
                </a-button>
              </a-space>
            </template>
            <a-table
              :dataSource="dataSourceList"
              :columns="BILL_COLUMNS"
              :pagination="false"
              rowKey="id"
              :loading="billLoading"
              :expandRowByClick="true"
              :expandedRowKeys="expandedRowKeys"
              @expand="expandRow"
              :scroll="{ x: 'max-content' }"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'contractOn'">
                  <template v-if="String(record.id).includes('carry')">
                    <cu-icon type="org-fenzhi" style="font-size: 18px"></cu-icon>
                    <span v-if="record.isInto">
                       <a-tag color="green">入</a-tag>
                      {{`从【${record.owner_name}】的【${record.village_name}-${record.build_name}-${record.roomInfo}】 【${record.contractOn}】期【${record.cost_type_txt}】账单中抵扣了【${record.amount}】元`}}
                    </span>
                    <span v-else>
                       <template v-if="record.father">
                         <a-tag color="red">出</a-tag>
                         {{`抵扣了【${record.father.owner_name}】的【${record.father.village_name}-${record.father.build_name}-${record.father.roomInfo}】 【${record.father.contractOn}】期【${record.father.cost_type_txt}】账单【${record.amount}】元`}}
                       </template>
                    </span>
                  </template>
                  <span v-else>{{text}}</span>
                </template>
                <template v-if="column.key === 'receivable_payment'">
                  <a-tag color="green">收</a-tag>
                  {{`￥${record.receivable_payment || 0}/￥${record.bill_amount || 0}`}}
                </template>
                <template v-if="column.key === 'receivable_latefee'">
                  {{`￥${record.receivable_latefee || 0}`}}
                </template>
                <template v-if="column.key === 'actual_payment'">
                  <a-tag color="green">收</a-tag>
                  {{`￥${record.actual_payment || 0}`}}
                </template>
                <template v-if="column.key === 'now_carry'">
                  <template v-if="record.now_carry">
                    <a-tag v-if="record.is_fu == 1" color="red">出</a-tag>
                    <a-tag v-else color="green">入</a-tag>
                  </template>
                  {{`￥${record.now_carry || 0}`}}
                </template>
                <template v-if="column.key === 'into_amount'">
                  <a-tag v-if="record.into_amount" color="green">入</a-tag>
                  {{`￥${record.into_amount || 0}`}}
                  <template v-if="record.out_amount">
                    <a-tag color="red" style="margin-left: 4px">出</a-tag>
                    {{`￥${record.out_amount}`}}
                  </template>
                </template>
                <template v-if="column.key === 'actual_retreat_now'">
                  <a-tag v-if="record.is_fu == 1" color="red">付</a-tag>
                  <a-tag v-else color="green">收</a-tag>
                  {{`￥${record.actual_retreat_now || 0}`}}
                </template>
                <template v-if="column.key === 'action'">
                  <a-button v-if="record.is_show_button == 1" type="link" @click.stop="handleCarryOver(record)">结转</a-button>
                  <span v-else>--</span>
                </template>
              </template>
              <template #summary>
                <a-table-summary-row v-if="dataSourceList?.length">
                  <a-table-summary-cell :col-span="2">总计</a-table-summary-cell>
                  <a-table-summary-cell>
                    <div>
                      <a-tag color="green">收</a-tag>
                      {{`￥${totalData.receivableObj.collection.amount}`}}/{{`￥${totalData.receivableObj.collection.original}`}}
                    </div>
                  </a-table-summary-cell>
                  <a-table-summary-cell>
                    {{`￥${totalData.receivable_latefee}`}}
                  </a-table-summary-cell>
                  <a-table-summary-cell>
                    <div>
                      <a-tag color="green">收</a-tag>
                      {{`￥${totalData.actual_payment.collection}`}}
                    </div>
                  </a-table-summary-cell>
                  <a-table-summary-cell>
                    <div>
                      <a-tag color="green">入</a-tag>
                      {{`￥${totalData.now_carry.collection}`}}
                    </div>
                    <div class="mt-5">
                      <a-tag color="red">出</a-tag>
                      {{`￥${totalData.now_carry.payment}`}}
                    </div>
                  </a-table-summary-cell>
                  <a-table-summary-cell>
                    <div>
                      <a-tag color="green">入</a-tag>
                      {{`￥${totalData.history_amount.into}`}}
                    </div>
                    <div class="mt-5">
                      <a-tag color="red">出</a-tag>
                      {{`￥${totalData.history_amount.out}`}}
                    </div>
                  </a-table-summary-cell>
                  <a-table-summary-cell>
                    <div>
                      <a-tag color="green">收</a-tag>
                      {{`￥${totalData.actual_retreat_now.collection}`}}
                    </div>
                    <div class="mt-5">
                      <a-tag color="red">付</a-tag>
                      {{`￥${totalData.actual_retreat_now.payment}`}}
                    </div>
                  </a-table-summary-cell>
                  <a-table-summary-cell></a-table-summary-cell>
                </a-table-summary-row>
              </template>
            </a-table>
          </a-card>
        </a-col>
        <a-col :span="24" class="mt-10">
          <a-card size="small" title="结转备注">
            <a-row :gutter="12">
              <a-col :span="24">
                <a-textarea
                  v-model:value="modelRef.remark"
                  placeholder="请输入结转备注"
                  :auto-size="{ minRows: 4, maxRows: 6 }"
                />
              </a-col>
            </a-row>
          </a-card>
        </a-col>
        <!--   附件   -->
        <a-col :span="24" class="mt-10">
          <attachment-info
              :params="attachParams"
              :addfolder="false"
              :batchupload="false"
              :object="false"
              @getObjectId="getObjectId"
          />
        </a-col>
      </a-row>
    </section>

    <section class="header" id="footer">
      <a-page-header
        class="demo-page-header"
        style="border: 1px solid rgb(235, 237, 240)"
        title=""
        sub-title=""
      >
        <div
          style="
            display: flex;
            justify-content: end;
            align-items: center;
          "
        >
          <a-space>
            <a-button
              @click="handleSubmit('draft')"
              :loading="submitLoading"
            >保存</a-button
            >
            <a-button
              @click="handleSubmit('approve')"
              :loading="submitLoading"
              type="primary"
            >保存&发起审批</a-button
            >
          </a-space>
        </div>
      </a-page-header>
    </section>


    <!--  结转  -->
    <AmountCarryOver
      :visible="carryVisible"
      :currentBill="currentBill"
      :contractId="id"
      @handleClose="handleCarryClose"
      @handleSubmit="handleCarrySubmit"
      :billList="billList"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  computed,
  createVNode,
  reactive,
  toRefs,
  nextTick,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import request from "../../../common/utils/request";
import moment from "moment";
import { TextTip } from "bl-common-vue3";
import {
  ExclamationCircleOutlined,
  FileTwoTone
} from "@ant-design/icons-vue";
import {Form, Modal, TableSummaryRow, TableSummaryCell, message} from "ant-design-vue";
import utils from "@/common/utils/utils";
import _ from "lodash";
import store from "@/store";
const useForm = Form.useForm;
import AmountCarryOver from "@/views/contract/NewCarryOver/modules/AmountCarryOver.vue";
import AttachmentInfo from "@/components/contract/AttachmentInfo/index.vue";
export default defineComponent({
  name: "contractCarryOver",
  components: {
    AttachmentInfo,
    TextTip,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    FileTwoTone,
    AmountCarryOver,
    ATableSummaryRow: TableSummaryRow,
    ATableSummaryCell: TableSummaryCell,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const notBack = $route.query.noBack;
    const id = ref(Number($route.query.id)); // 合同id
    const task_key = ref($route.query.task_key);

    const title = computed(() => {
      return task_key.value ? '编辑结转' : '新建结转';
    });

    const state = reactive({
      submitLoading: false,
      hiddenZero: false,
      billLoading: false,
      billList: [],
      expandedRowKeys: [],
      contractDetail: {},
      carryVisible: false,
      currentBill: {},
      fastLoading: false,
      attachParams: {
        object_id: '',
        type: 1,
      },
      object_id:'',
    });

    const getObjectId = (id) => {
      state.object_id = id;
    };

    const modelRef = reactive({
      remark: '',
    });

    const rulesRef = reactive({
    });

    const { validate, validateInfos } = useForm(modelRef, rulesRef);

    const expandRow = (e, record) => {
      if (e) {
        state.expandedRowKeys.push(record.id);
      } else {
        state.expandedRowKeys.splice(
          state.expandedRowKeys.indexOf(record.id),
          1
        );
      }
    };

    // 总计
    const totalData = computed(() => {
      let collectionList = dataSourceList.value.filter((v) => v.is_fu != 1);
      let paymentList = dataSourceList.value.filter((v) => v.is_fu == 1);
      return {
        receivableObj: {
          collection: {
            amount: dataSourceList.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.receivable_payment)]), 0),
            original: dataSourceList.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.bill_amount)]), 0),
          },
        },
        receivable_latefee: dataSourceList.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.receivable_latefee)]), 0),
        actual_payment: {
          collection: dataSourceList.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.actual_payment)]), 0),
        },
        now_carry: {
          collection: collectionList.reduce((acc, cur) => utils.countSum([acc, Number(cur.now_carry)]), 0),
          payment: paymentList.reduce((acc, cur) => utils.countSum([acc, Number(cur.now_carry)]), 0),
        },
        history_amount: {
          into: dataSourceList.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.into_amount)]), 0),
          out: dataSourceList.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.out_amount)]), 0),
        },
        actual_retreat_now: {
          collection: collectionList.reduce((acc, cur) => utils.countSum([acc, Number(cur.actual_retreat_now)]), 0),
          payment: paymentList.reduce((acc, cur) => utils.countSum([acc, Number(cur.actual_retreat_now)]), 0),
        }
      }
    });

    // 需收付 非0 的账单
    const actualRetreatNoZeroList = computed(() => {
      return state.billList.filter((v) => Number(v.actual_retreat_now) !== 0)
    });

    const dataSourceList = computed(() => {
      return state.hiddenZero ? actualRetreatNoZeroList.value : state.billList;
    });

    const handleCarryOver = (record) => {
      state.carryVisible = true;
      state.currentBill = record;
    };

    const handleCarryClose = () => {
      state.carryVisible = false;
      state.currentBill = {};
    };

    const getIntoBillMap = () => {
      const childrenData = state.billList.filter(item => item.children && item.children.length > 0 && item.is_fu != 1).map(item => item.children).flat();
      const billsMap = childrenData.reduce((acc, item) => {
        if (acc[item.bill_id]) {
          acc[item.bill_id].push(_.cloneDeep(item));
        } else {
          acc[item.bill_id] = [_.cloneDeep(item)];
        }
        return acc;
      }, {});
      state.billList.forEach((item) => {
        if (item.is_fu == 1) {
          if (billsMap[item.id]) {
            item.children = _.cloneDeep(billsMap[item.id]).map((v) => {v.isInto = false; return v});
            const totalObj = getActualAmount(item.actual_retreat, item.children);
            item.actual_retreat_now = totalObj.surplusTotal;
            item.now_carry = totalObj.amountTotal;
          } else {
            delete item.children;
            item.actual_retreat_now = item.actual_retreat;
            item.now_carry = 0;
          }
        }
      })
    };

    const handleSubmit = (type) => {
      let params = {...modelRef};
      params.status = type == 'draft' ? 0 : 1;
      if (task_key.value) {
        params.task_key = task_key.value;
      }
      let data = _.cloneDeep(state.billList).filter((v) => v.is_fu != 1 && v?.children?.length);
      let dataList = data.map((v) => {
        return {
          origin_bill_id: v.bill_id,
          from_bill_info: v.children.map((item) => {
            return {
              from_bill_id: item.bill_id,
              amount: item.amount,
            }
          }),
        }
      });
      params.data = dataList;
      params.object_id = state.object_id;
      state.submitLoading = true;
      request
        .post("/org", "/billTransfer/addTransfer", params)
        .then((res) => {
          message.success(res.msg || "保存成功");
          state.submitLoading = false;
          goBack();
        }).catch(() => {
        state.submitLoading = false;
      });
    };

    const getDetail = () => {
      request
        .get("/org", "/create/contractInfo", { id: id.value })
        .then((res) => {
          state.contractDetail = res || {};
        });
    };

    const getActualAmount = (originAmount, amountList) => {
      // 原始金额 减去 其余账单结转金额
      let total = amountList.reduce((acc, cur) => utils.countSum([acc, Number(cur.amount)]), 0);
      return {
        amountTotal: total,
        surplusTotal: utils.countSum([Number(originAmount), -Number(total)]),
      };
    };

    const handleCarrySubmit = (rows, id) => {
      const set = new Set(state.expandedRowKeys);
      state.billList.forEach((item) => {
        if (item.id == id) {
          if (rows?.length) {
            set.add(id);
            item.children = rows.map((v) => {
              v.father = item;
              return v;
            });
            const totalObj = getActualAmount(item.actual_retreat, item.children);
            item.actual_retreat_now = totalObj.surplusTotal;
            item.now_carry = totalObj.amountTotal;
          } else {
            set.delete(id);
            delete item.children;
            item.actual_retreat_now = item.actual_retreat;
            item.now_carry = 0;
          }
        }
      })
      handleCarryClose();
      getIntoBillMap();
      state.expandedRowKeys = Array.from(set);
    };

    const getBillList = () => {
      state.billLoading = true;
      request
        .get("/org", "/billTransfer/contractTransferList", { contract_id: id.value})
        .then((res) => {
          let data = res?.list || [];
          data = data.map((item) => {
            item.id = item.bill_id;
            item.actual_retreat_now = item.actual_retreat;
            return item;
          })
          state.billList = data;
          state.billLoading = false;
        }).catch(() => {
        state.billLoading = false;
      });
    };

    const handleProcessData = (sourceData) => {
      sourceData = sourceData.map((item) => {
        item.id = item.bill_id;
        if (item.children && item.children.length) {
          item.children = item.children.map((v) => {
            v.id = `carry_${v.bill_id}`;
            v.isInto = true;
            v.father = item;
            return v;
          });
          const totalObj = getActualAmount(item.actual_retreat, item.children);
          item.actual_retreat_now = totalObj.surplusTotal;
          item.now_carry = totalObj.amountTotal;
        } else {
          delete item.children;
          item.actual_retreat_now = item.actual_retreat;
          item.now_carry = 0;
        }
        return item;
      })
      state.billList = sourceData;
      getIntoBillMap();
    };

    // 快捷结转
    const handleFastCarry = () => {
      Modal.confirm({
        title: () => "提示",
        content: "若合同未退租，则会进行新老合同的账单之间的快捷结转。\n若合同已退租，则只进行本合同内部的账单之间的快捷结转。\n快捷结转后，仍可手动调整结转账单及结转金额，是否继续？",
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          state.fastLoading = true;
          request
            .get("/org", "/billTransfer/antoTransfer", { contract_id: id.value})
            .then((res) => {
              let sourceData = res?.list || [];
              handleProcessData(sourceData);
              state.fastLoading = false;
            }).catch(() => {
            state.fastLoading = false;
          });
        },
      });
    };

    const goBack = () => {
      if (window.history.state.back) {
        $router.back();
      } else {
        $router.replace({
          name: "contractList",
        });
      }
    };

    const getDetailList = (init) => {
      state.billLoading = true;
      request
        .get("/org", "/billTransfer/transferDetail", { contract_id: id.value, task_key: task_key.value})
        .then((res) => {
          if (init) {
            modelRef.remark = res?.remark || '';
          }
          let sourceData = res?.list || [];
          state.attachParams.object_id = $route.query.task_key ? res.object_id : ''
          handleProcessData(sourceData);
          state.billLoading = false;
        }).catch(() => {
        state.billLoading = false;
      });
    };

    const getSourceData = (init = false) => {
      if (task_key.value) {
        // 编辑
        getDetailList(init);
      } else {
        // 新建
        getBillList();
      }
    };


    const init = () => {
      getDetail();
      getSourceData(true);
    };

    const resetTableData = () => {
      getSourceData(false);
    }


    init();


    return {
      id,
      ...toRefs(state),
      validateInfos,
      modelRef,
      BILL_COLUMNS,
      totalData,
      dataSourceList,
      title,
      handleSubmit,
      expandRow,
      handleCarryOver,
      handleCarryClose,
      handleCarrySubmit,
      resetTableData,
      handleFastCarry,
      getObjectId,

      notBack
    };
  },
});

const BILL_COLUMNS = [
  {
    title: "区间",
    dataIndex: "contractOn",
    key: "contractOn",
    customCell: (record, rowIndex) => {
      return {
        colSpan:
          String(record.id).includes('carry') ? 9 : 1,
      };
    },
  },
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "应收金额/原始应收",
    dataIndex: "receivable_payment",
    key: "receivable_payment",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "滞纳金",
    dataIndex: "receivable_latefee",
    key: "receivable_latefee",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "实收",
    dataIndex: "actual_payment",
    key: "actual_payment",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "本次结转",
    dataIndex: "now_carry",
    key: "now_carry",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "历史结转",
    dataIndex: "into_amount",
    key: "into_amount",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "需收/付",
    dataIndex: "actual_retreat_now",
    key: "actual_retreat_now",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "操作",
    dataIndex: "id",
    align: "center",
    key: "action",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
            ? "none"
            : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
];
</script>

<style lang="less" scoped>
.new-carry-over {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    background-color: #fff;

    :deep(.ant-list-item-meta-avatar) {
      margin-right: 32px;
      margin-left: 16px;
      margin-top: 10px;
    }

    :deep(.ant-page-header) {
      padding-bottom: 0;
    }
  }

  .content {
    flex: 1;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: auto;

    .bill-card {
      :deep(.ant-alert-info) {
        background-color: #fafafa;
        border: none;
      }

      :deep(.ant-alert-message) {
        text-align: right;
        padding-right: 10px;
      }
    }
  }

  #footer {
    :deep(.ant-page-header) {
      padding-bottom: 20px;
    }
  }
}
:deep(.ant-tag) {
  margin-right: 4px;
}
:deep(.ant-table) {
  .ant-table-tbody tr:nth-child(2n) td {
    background-color: initial !important;
  }
}
:deep(.ant-table-row-level-1) {
  background-color: #e0e0e0 !important;
  td {
    padding: 8px 16px;
  }
}
.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}
</style>
